export const platform = (function () {
    const u = navigator.userAgent
    const app = navigator.appVersion
    return {
        trident: u.indexOf('Trident') > -1, // IE内核
        presto: u.indexOf('Presto') > -1, // opera内核
        webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // 火狐内核
        mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
        android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, // android终端
        iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
        iPad: u.indexOf('iPad') > -1, // 是否iPad
        webApp: u.indexOf('Safari') === -1, // 是否web应该程序，没有头部与底部
        weixin: u.indexOf('MicroMessenger') > -1, // 是否微信 （2015-01-22新增）
        qq: u.match(/\sQQ/i) === ' qq' // 是否QQ
    }
})

// 参数报错处理
export const convertValue = value => (value || 0)
// Vue.filter('convertValue', convertValue);


// 验证手机号
export const isPhoneNumber = (str) => {
    const reg = /^1[34578]\d{9}$/
    return reg.test(str)
}

// 大陆身份证校验
export function validIdCard (idCard) {
    const reg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/
    return reg.test(idCard)
}

// 香港身份证校验
export function validHkCard (hkCard) {
    const reg = /^((\s?[A-Za-z])|([A-Za-z]{2}))\d{6}(\([0−9aA]\)|[0-9aA])$/
    return reg.test(hkCard)
}

// 中文校验
export function validChinese (str) {
    const reg = /^[\u4e00-\u9fa5]+$/
    return reg.test(str)
}

// 日期
export const dateFormat = function (date, fmt = 'YYYY-MM-DD') {
    let newDate = date

    let fmts = fmt

    // console.log(fmt)
    // fmts='YYYY-MM-DD HH:mm:ss'
    if (!newDate) {
        newDate = new Date()
    }
    if (typeof +newDate === 'number') {
        newDate = new Date(newDate)
    }
    const o = {
        'M+': newDate.getMonth() + 1,
        'D+': newDate.getDate(),
        'h+': newDate.getHours() % 12 === 0 ? 12 : newDate.getHours() % 12,
        'H+': newDate.getHours(),
        'm+': newDate.getMinutes(),
        's+': newDate.getSeconds(),
        'q+': Math.floor((newDate.getMonth() + 3) / 3),
        S: newDate.getMilliseconds()
    }
    const week = {
        0: '\u65e5',
        1: '\u4e00',
        2: '\u4e8c',
        3: '\u4e09',
        4: '\u56db',
        5: '\u4e94',
        6: '\u516d'
    }
    if (/(Y+)/.test(fmts)) {
        fmts = fmts.replace(RegExp.$1, (`${newDate.getFullYear()}`).substr(4 - RegExp.$1.length))
    }
    if (/(E+)/.test(fmts)) {
        fmts = fmts.replace(RegExp.$1, () => {
            if (RegExp.$1.length > 1) {
                if (RegExp.$1.length > 2) {
                    return `\u661f\u671f${week[newDate.getDay()]}`
                }
                return `\u5468${week[newDate.getDay()]}`
            }
            return week[`${newDate.getDay()}`]
        })
    }
    Object.keys(o)
        .forEach((k) => {
            if (new RegExp(`(${k})`).test(fmts)) {
                fmts = fmts.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : ((`00${o[k]}`).substr((`${o[k]}`).length)))
            }
        })
    return fmts
}
export default {
    /**
     * 替换指定传入参数的值,paramName为参数,replaceWith为新值
     * @param paramName
     * @param replaceWith
     */
    replaceParamVal (url, paramName, replaceWith) {
        var re = eval('/(' + paramName + '=)([^&]*)/gi');
        var nUrl = url.replace(re, paramName + '=' + replaceWith);
        return nUrl;
    },
    /**
     * 获取URL参数 例：var nameVal=GetQueryString("URL上的参数名");
     * @param name
     * @returns {null}
     * @constructor
     */
    GetQueryString (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return null;
    },
    randomStr (length) {
        return Math.random().toString(36).substr(2).slice(1, 1 + length)
    },
    /**
     * 删除URL中的指定参数
     * @param {*} url 
     * @param {*} name 
     */
    delUrlParams (url, name) {
        var urlArr = url.split('?');
        if (urlArr.length > 1 && urlArr[1].indexOf(name) > -1) {
            var query = urlArr[1];
            var obj = {}
            var arr = query.split("&");
            for (var i = 0; i < arr.length; i++) {
                arr[i] = arr[i].split("=");
                obj[arr[i][0]] = arr[i][1];
            };
            delete obj[name];
            var urlte = urlArr[0] + '?' + JSON.stringify(obj).replace(/[\"\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&");
            return urlte;
        } else {
            return url;
        };
    },
    sha1 (s) {
        var data = new Uint8Array(this.encodeUTF8(s))
        var i, j, t;
        var l = ((data.length + 8) >>> 6 << 4) + 16, s = new Uint8Array(l << 2);
        s.set(new Uint8Array(data.buffer)), s = new Uint32Array(s.buffer);
        for (t = new DataView(s.buffer), i = 0; i < l; i++) s[i] = t.getUint32(i << 2);
        s[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
        s[l - 1] = data.length << 3;
        var w = [], f = [
            function () {
                return m[1] & m[2] | ~m[1] & m[3];
            },
            function () {
                return m[1] ^ m[2] ^ m[3];
            },
            function () {
                return m[1] & m[2] | m[1] & m[3] | m[2] & m[3];
            },
            function () {
                return m[1] ^ m[2] ^ m[3];
            }
        ], rol = function (n, c) {
            return n << c | n >>> (32 - c);
        },
            k = [1518500249, 1859775393, -1894007588, -899497514],
            m = [1732584193, -271733879, null, null, -1009589776];
        m[2] = ~m[0], m[3] = ~m[1];
        for (i = 0; i < s.length; i += 16) {
            var o = m.slice(0);
            for (j = 0; j < 80; j++)
                w[j] = j < 16 ? s[i + j] : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1),
                    t = rol(m[0], 5) + f[j / 20 | 0]() + m[4] + w[j] + k[j / 20 | 0] | 0,
                    m[1] = rol(m[1], 30), m.pop(), m.unshift(t);
            for (j = 0; j < 5; j++) m[j] = m[j] + o[j] | 0;
        }
        ;
        t = new DataView(new Uint32Array(m).buffer);
        for (var i = 0; i < 5; i++) m[i] = t.getUint32(i << 2);

        var hex = Array.prototype.map.call(new Uint8Array(new Uint32Array(m).buffer), function (e) {
            return (e < 16 ? "0" : "") + e.toString(16);
        }).join("");
        return hex;
    },
    encodeUTF8 (text) {
        const code = encodeURIComponent(text);
        const bytes = [];
        for (var i = 0; i < code.length; i++) {
            const c = code.charAt(i);
            if (c === '%') {
                const hex = code.charAt(i + 1) + code.charAt(i + 2);
                const hexVal = parseInt(hex, 16);
                bytes.push(hexVal);
                i += 2;
            } else bytes.push(c.charCodeAt(0));
        }
        return bytes;
    },

    // 判断是否在微信浏览器打开
    is_weixn () {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
            //TODO
            return true
        } else {
            //TODO
            return false
        }
    },
    // 分页加载数据 后台拿到数据，前端进行渲染，数据多的情况下要进行分页显示，提升用户体验，减少过的请求造成不必要的数据浪费和卡顿
    //获取滚动条当前的位置 

    getScrollTop () {
        var scrollTop = 0;
        if (document.documentElement && document.documentElement.scrollTop) {
            scrollTop = document.documentElement.scrollTop;
        } else if (document.body) {
            scrollTop = document.body.scrollTop;
        }
        return scrollTop;
    },
    //获取当前可视范围的高度 
    getClientHeight () {
        var clientHeight = 0;
        if (document.body.clientHeight && document.documentElement.clientHeight) {
            clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
        } else {
            clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
        }
        return clientHeight;
    },
    //获取文档完整的高度 
    getScrollHeight () {
        return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
    },
    lanjiazai () {
        //分页加载数据实现
        window.onscroll = function () {
            if (that.getScrollTop() + that.getClientHeight() == that.getScrollHeight()) {
                axios.post(apiurl, {
                    // 'page': that.page++; //滑动到底部让页码数+1
                }).then(function (res) {
                    data = data.concat(res.data.data.data);//使用js数组的concat方法将数据拼接起来.
                })
                    .catch(function (error) {
                        console.log(error);
                    });
            }
        }
    },
    // 分页加载数据 后台拿到数据，前端进行渲染，数据多的情况下要进行分页显示，提升用户体验，减少过的请求造成不必要的数据浪费和卡顿结束

    // 获取验证码倒计时
    time (yzmBtn, yzmTip) {
        if (wait < 0) {
            that.yzmTip = "获取验证码"
            that.yzmBtn = false
            wait = 60;
        } else {
            that.yzmBtn = true;
            that.yzmTip = wait + "秒后获取";
            wait--;
            setTimeout(function () {
                time();
            }, 1000)
        }
    },
    // 银行卡校验
    luhnCheck (num) {
        let arr = (num + '')
            .split('')
            .reverse()
            .map(x => parseInt(x));
        let lastDigit = arr.splice(0, 1)[0];
        let sum = arr.reduce((acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val * 2) % 9) || 9), 0);
        sum += lastDigit;
        return sum % 10 === 0;
    },


}